/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.handler;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import cn.ac.iie.di.ban.commons.RuntimeEnv;
import cn.ac.iie.di.ban.metastore.Load2DBEntity;
import java.util.Map;

/**
 *
 * @author sxl
 */
public abstract class SE2DBWorker implements Runnable {

    private static org.apache.log4j.Logger logger = Logger.getLogger(SE2DBWorker.class.getName());
    protected HttpSe2DBHandler httpSe2DBHandler;
    protected Load2DBEntity load2DBEntity;
    int batchSize;
    List<Map<String, Object>> docRecordSet = new ArrayList(1);
    long lastUpdateTime = -1;
    int timeout = -1;
    protected volatile boolean stopped;
    protected String dwType;
    protected Long start_time = -1L;
    protected Long end_time = -1L;
    private List<String> result = new ArrayList<>(1);

    public SE2DBWorker(HttpSe2DBHandler httpSe2DBHandler, String pDWType) {
        this.httpSe2DBHandler = httpSe2DBHandler;
        batchSize = httpSe2DBHandler.getLoadNum();
        load2DBEntity = httpSe2DBHandler.getLoad2MBEntity();
        dwType = pDWType;
        stopped = false;
        timeout = (Integer) RuntimeEnv.getParam(RuntimeEnv.TIMEOUT);
    }

    public void run() {
        Thread.currentThread().setName("load msg " + dwType + " worker_" + System.nanoTime());
        while (true) {
            Map<String, Object> data = httpSe2DBHandler.getData();
            if (data == null) {
                if (stopped) {
                    logger.info("prepare to exit...");
                    freeSource();
                    break;
                }
                try {
                    Thread.sleep((Integer) RuntimeEnv.getParam(RuntimeEnv.WAIT_TIME));
                } catch (Exception ex) {
                }
            } else {
                loadData(data);
            }
        }
        logger.info(Thread.currentThread().getName() + " exited");
    }

    public void shutdown() {
        stopped = true;
    }

    public abstract void freeSource();

    public void loadData(Map<String, Object> pRecordSet) {
        docRecordSet.add(pRecordSet);
        loadData0();
        docRecordSet.clear();
    }

    public abstract void init() throws Exception;

    public abstract void loadData0();
}
